<template>
  <div class="employees-container">
    <div class="app-container">

      <PageTools>
        <!-- 左侧插槽 -->
        <template #slot-left>
          <span>总共{{ total }}条</span>
        </template>

        <!-- 右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="addfn">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 列表主体部分 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="tablelist" :default-sort="{prop:'workNumber'}">
          <el-table-column type="index" label="序号" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <ImageHolder :imgsrc="scope.row.staffPhoto" />

            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />

          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatter" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间">
            <template slot-scope="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setEmp(scope.row)">分配角色</el-button>
              <el-button type="text" size="small" @click="delfn(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->

        <!-- 分页区域 -->
        <el-pagination
          :current-page="query.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 弹框 新增员工-->
        <el-dialog
          title="新增员工"
          :visible.sync="dialogVisible"
          width="70%"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="closefn"
        >
          <EmpDialog ref="empform" @close="empclose" @updataform="updataformfn" />

        </el-dialog>
        <!-- 弹框 分配角色 -->
        <el-dialog
          title="分配角色"
          :visible.sync="showRoleDialog"
          width="70%"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="showRoleDialog=false"
        >
          <AssignRole v-if="showRoleDialog" :use-id="useId" @close="showRoleDialog = false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getuserinfo, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'
import dayjs from 'dayjs'
export default {
  components: {
    EmpDialog,
    AssignRole
  },
  filters: {
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    }

  },
  data() {
    return {
      total: 0,
      query: {
        page: 1,
        size: 10
      },
      tablelist: [],
      dialogVisible: false, // 新增员工的弹框的显示与隐藏
      showRoleDialog: false, // 分配角色弹框的显示与隐藏
      useId: ''
    }
  },
  created() {
    // 调用获取员工列表
    this.getuserinfo()
  },
  methods: {
    // 对数据进行格式化处理
    transData(rows) {
      // 枚举的数据
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // rows现在是[{name:值,age:值},{name:值,age:值}]  rows[0]拿到第一项对象 {key:值,key:值,key:值}
      const headerKeys = Object.keys(rows[0]) // headerKeys是个数组[key,key,key]

      const header = headerKeys.map(item => {
        return map[item]
      })

      const data = rows.map(item => {
        return Object.values(item)
        // Object.values 将所以是值形成一个数值  map也形成一个数组[[值,值,值],[值,值,值]]
      })
      return { data, header }
    },
    // 点击导入excel
    async downloadExcel() {
      // 请求从后端传过来的最新数据
      const res = await getuserinfo(this.query)
      // 调用格式化数据 获取data 和 header
      const excelObj = this.transData(res.data.rows)
      //   console.log(excelObj)
      // 设置后端返回表头和数据
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工列表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 每页的数据数量
    handleSizeChange(newsize) {
      this.query.size = newsize
      //   console.log(1)
      this.getuserinfo()
    },
    // 改变当前页
    handleCurrentChange(newpage) {
      this.query.page = newpage
      //   console.log(2)
      this.getuserinfo()
    },
    // 获取员工列表
    async getuserinfo() {
      const res = await getuserinfo(this.query)
      //   console.log(res)
      this.tablelist = res.data.rows
      this.total = res.data.total
    },
    // 枚举格式化形式
    formatter(row, column, cellValue, index) {
    //   console.log(cellValue)
      const res = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return res ? res.value : '未知'
    },
    // 点击删除
    async delfn(row) {
      const res = await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'cancel') return this.$message('取消删除')
      if (this.tablelist === 1) {
        this.query.page--
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }
      const res1 = await delEmployee(row.id)
      this.$message.success(res1.message)
      this.getuserinfo()
    },
    // 点击新增员工
    addfn() {
      this.dialogVisible = true
    },
    // 点击弹框关闭
    closefn() {
      this.$refs.empform.restform()// 重置表单
    },
    // 点击取消按钮
    empclose() {
      this.dialogVisible = false
    },
    // 点击确定提交表单后
    updataformfn() {
      this.dialogVisible = false
      this.getuserinfo()
    },
    // 点击分配角色
    setEmp(row) {
      this.showRoleDialog = true// 弹框显示
      this.useId = row.id
    }

  }
}
</script>

<style lang="scss" scoped>
.el-pagination{
    text-align: center;
    margin-top: 20px;
}
.el-table .cell img {
    height: 100px;
}
</style>
